import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Link, useNavigate } from "react-router-dom";
import { DownOutlined } from "@ant-design/icons";
import { Dropdown, Menu, Space, message as messagecom } from "antd";
import React, { useState, useEffect } from "react";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import { Messagewrap } from "./styled";
import {
  changethumbapi,
  deletemessageapi,
  getallmessage,
  replyapi,
} from "@/apis/message";
import { formattime } from "@/utils";
import { shallowEqual, useDispatch, useSelector } from "react-redux";
import { rootState } from "@/store";
import { usertype } from "@/store/reducers/home";
import classNames from "classnames";
import { getcollectidarraction, loginpatch } from "@/store/action/home";
import Routertran from "@/components/routertran";
interface messagestate {
  id: number;
  content: string;
  createAt: string;
  thumbcount: number;
  replyname: string;
  user_id: number;
  author: {
    id: number;
    username: string;
    avatar: string;
  };
  childmessage: messagestate[];
}
function MyEditor() {
  const dispatch = useDispatch<any>();
  const navigate = useNavigate();

  const [editor, setEditor] = useState<IDomEditor | null>(null); // 存储 editor 实例
  const [message, setMessage] = useState<messagestate[]>([]);
  const [expand, setExpand] = useState<boolean[]>(); //保存回复的评论是否展开
  const [replyobj, setRlyobj] = useState<{
    messageid: number;
    content: string;
  }>({ messageid: -1, content: "" }); //回复的对象
  const [placeholder, setPlaceholder] = useState("请发表和善的言论");

  const { user, messagethumbarr } = useSelector(
    (store: rootState) => ({
      user: store.home.user as usertype,
      messagethumbarr: store.home.thumbdobj.messagearr,
    }),
    shallowEqual
  );
  const toolbarConfig: Partial<IToolbarConfig> = {
    excludeKeys: [
      "headerSelect",
      "italic",
      "group-more-style", // 排除菜单组，写菜单组 key 的值即可
      "fullScreen",
      "divider",
      "group-video",
      "underline",
      "group-more-style",
      "bold",
      "group-image",
      "insertTable",
    ],
  };
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: placeholder,
  };

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  //获取所有留言
  useEffect(() => {
    getallmessagefn();
  }, []);
  //是否展开的数组
  useEffect(() => {
    if (!message) return;
    //说明是初始化
    if (!expand) {
      return setExpand(Array(message.length).fill(false));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [message]);

  //展开或者收起
  const changeexpand = (index: number) => {
    if (!expand) return;
    const arr = expand.slice();
    arr[index] = !arr[index];
    setExpand(arr);
  };
  //改变回复对象
  const changereply = (messageid: number, content: string) => {
    if (!user.id) return messagecom.error("请登录");
    setRlyobj((x) => ({ ...x, messageid }));
    setPlaceholder(content);
  };
  //取消回复
  const canclereply = () => {
    setRlyobj((x) => ({ ...x, messageid: -1 }));
    setPlaceholder("");
  };
  //回复留言
  const reply = async () => {
    if (!user.id) return messagecom.error("请登录");
    try {
      await replyapi(user.id, replyobj.messageid, replyobj.content);
      //说明在最上面添加了一条评论，要保持展开的状态
      if (replyobj.messageid === -1 && expand) {
        setExpand([false, ...expand?.slice()]);
      }
      setRlyobj({ content: "", messageid: -1 });
      setPlaceholder("");
      getallmessagefn();
    } catch (e) {
      dispatch(loginpatch({}));
      messagecom.error("身份失效");
    }
  };
  //删除留言
  const deletemessage = async (id: number) => {
    try {
      await deletemessageapi(id);
      // 保证展开状态
      const index = message.map((item) => item.id).indexOf(id);
      if (index > -1 && expand) {
        setExpand([...expand?.slice(0, index), ...expand.slice(index + 1)]);
      }
      getallmessagefn();
    } catch (e) {
      dispatch(loginpatch({}));
      messagecom.error("身份失效");
    }
  };
  //点赞或取消点赞
  const changethumb = async (message_id: number) => {
    try {
      await changethumbapi(message_id, user.id);
      dispatch(getcollectidarraction(user.id));
      getallmessagefn();
    } catch (e) {
      dispatch(loginpatch({}));
      messagecom.error("身份失效");
    }
  };

  //获取所有留言
  const getallmessagefn = () => {
    getallmessage().then((res: any) => {
      setMessage(res.result);
    });
  };
  return (
    <Messagewrap>
      <div className="content">
        <div className="editor">
          <Toolbar
            editor={editor}
            defaultConfig={toolbarConfig}
            mode="default"
            style={{ borderBottom: "1px solid #ccc" }}
          />
          <Editor
            defaultConfig={editorConfig}
            value={replyobj.content}
            onCreated={setEditor}
            onChange={(editor) =>
              setRlyobj((x) => {
                if (editor.getHtml() === "<p><br></p>")
                  return { ...x, content: "" };
                return { ...x, content: editor.getHtml() };
              })
            }
            mode="default"
            style={{ height: "250px" }}
          />
        </div>
        <div className="bt">
          <span>
            欢迎留言，互换友链请移步 <Link to={"/lin"}>友邻</Link> 页面申请
          </span>
          <span onClick={canclereply}>
            {replyobj.messageid !== -1 && "回复 @" + placeholder}
          </span>
          <span
            className={classNames({
              active: replyobj.content !== "",
            })}
            onClick={reply}
          >
            评论
          </span>
        </div>
        <ul className="maincontent">
          {message ? (
            message.map((item, index) => (
              <>
                <li key={item.id}>
                  <div className="main">
                    <img
                      src={item.author.avatar}
                      alt=""
                      onClick={(e) => navigate(`/userpage/${item.author.id}`)}
                    />
                    <div className="main">
                      <div className="username">{item.author.username}</div>
                      <div className="content">
                        <Editor
                          value={item.content}
                          defaultConfig={{ readOnly: true }}
                        ></Editor>
                      </div>
                      <div className="time">
                        {formattime(item.createAt)}
                        <span
                          className={classNames({
                            "iconfont icon-jushoucanggift": true,
                            iconfontactive: messagethumbarr.includes(item.id),
                          })}
                          onClick={(e) => changethumb(item.id)}
                        ></span>
                        {item.thumbcount}
                      </div>
                    </div>
                    <Dropdown
                      className="dropdown"
                      overlay={
                        <Menu
                          items={[
                            {
                              label: (
                                <div
                                  className="reply"
                                  style={{ color: "blue" }}
                                  onClick={(e) => {
                                    changereply(item.id, item.author.username);
                                  }}
                                >
                                  回复
                                </div>
                              ),
                              key: "0",
                            },
                            {
                              label: user.id === item.user_id && (
                                <div
                                  className="delete"
                                  style={{ color: "red" }}
                                  onClick={(e) => {
                                    deletemessage(item.id);
                                  }}
                                >
                                  删除
                                </div>
                              ),
                              key: "1",
                            },
                          ]}
                        />
                      }
                      trigger={["click"]}
                    >
                      <Space>
                        <DownOutlined style={{ cursor: "pointer" }} />
                      </Space>
                    </Dropdown>
                  </div>
                  {expand && expand[index] && (
                    <ul>
                      {item.childmessage.map((childitem) => (
                        <li key={childitem.id}>
                          <img src={childitem.author.avatar} alt="" />
                          <div className="main">
                            <div className="username">
                              {childitem.author.username +
                                " 回复@" +
                                childitem.replyname}
                            </div>
                            <div className="content">
                              <Editor
                                value={childitem.content}
                                defaultConfig={{ readOnly: true }}
                              ></Editor>
                            </div>
                            <div className="time">
                              {formattime(childitem.createAt)}
                              <span
                                className={classNames({
                                  "iconfont icon-jushoucanggift": true,
                                  iconfontactive: messagethumbarr.includes(
                                    childitem.id
                                  ),
                                })}
                                onClick={(e) => changethumb(childitem.id)}
                              ></span>
                              {childitem.thumbcount}
                            </div>
                          </div>
                          <Dropdown
                            className="dropdown"
                            overlay={
                              <Menu
                                items={[
                                  {
                                    label: (
                                      <div
                                        className="reply"
                                        style={{ color: "blue" }}
                                        onClick={(e) => {
                                          changereply(
                                            childitem.id,
                                            childitem.author.username
                                          );
                                        }}
                                      >
                                        回复
                                      </div>
                                    ),
                                    key: "0",
                                  },
                                  {
                                    label: user.id === childitem.user_id && (
                                      <div
                                        className="delete"
                                        style={{ color: "red" }}
                                        onClick={(e) => {
                                          deletemessage(childitem.id);
                                        }}
                                      >
                                        删除
                                      </div>
                                    ),
                                    key: "1",
                                  },
                                ]}
                              />
                            }
                            trigger={["click"]}
                          >
                            <Space>
                              <DownOutlined style={{ cursor: "pointer" }} />
                            </Space>
                          </Dropdown>
                        </li>
                      ))}
                    </ul>
                  )}
                  {item.childmessage.length > 0 && (
                    <span
                      className="expand"
                      onClick={(e) => changeexpand(index)}
                    >
                      {expand && expand[index]
                        ? "收起"
                        : "展开" + item.childmessage.length + "条回复"}
                    </span>
                  )}
                </li>
              </>
            ))
          ) : (
            <Routertran
              width={200}
              height={150}
              top={300}
              left={200}
            ></Routertran>
          )}
        </ul>
        {/* <div style={{ marginTop: "15px" }}>{html}</div> */}
      </div>
    </Messagewrap>
  );
}

export default MyEditor;
